<template>
  <div>
    <div class="title">
        <span>分账关系配置</span>
        <span :key="key"></span>
        <div>
            <el-button type="primary" @click="addRelation">添加分账关系</el-button>
            <el-button
            icon="el-icon-refresh"
            @click.native="updateClick()"
            ></el-button>
        </div>
    </div>
    <div class="container">
      <!-- 搜索板块 -->
      <div class="screeningBox">
          <el-form ref="searchForm" :model="searchForm">
              <div class="leftBox" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="merchantNo">
                          <el-input placeholder="分账商户号"  v-model="searchForm.merchantNo"></el-input>
                      </el-form-item>
                  </div>
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="merchantName">
                          <el-input placeholder="分账商户名" v-model="searchForm.merchantName"></el-input>
                      </el-form-item>
                  </div>
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="channelMerchantNo">
                          <el-input placeholder="分账通道号" v-model="searchForm.channelMerchantNo"></el-input>
                      </el-form-item>
                  </div>
              </div>
              <div class="leftBox">
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="splitMerchantNo">
                          <el-input placeholder="被分账商户号"  v-model="searchForm.splitMerchantNo"></el-input>
                      </el-form-item>
                  </div>
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="splitMerchantName">
                          <el-input placeholder="被分账商户名" v-model="searchForm.splitMerchantName"></el-input>
                      </el-form-item>
                  </div>
                  <div class="leftitem">
                      <el-form-item class="ipt" prop="splitChannelMerchantNo">
                          <el-input placeholder="被分账通道号" v-model="searchForm.splitChannelMerchantNo"></el-input>
                      </el-form-item>
                  </div>
              </div>
              <div class="rightBox">
                 
                  <div class="leftitem">
                   
                  </div>
                  <div class="leftitem">
                      <el-form-item>
                          <el-button icon="el-icon-search" type="primary" @click="soso" :disabled="isDisable">
                              搜索
                          </el-button>
                          <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
                      </el-form-item>
                  </div>
              </div>
          </el-form>
      </div>
      <!-- 表格板块 -->
      <div class="tableBox">
        <el-table
        ref="multipleTable"
        :data="relationData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        v-loading="loading"
        :header-cell-style="tableHeaderColor">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
              prop="id"
              align="center"
              label="序号"
              width="50"
          ></el-table-column>
          <el-table-column
              prop="merchantNo"
              label="分账商户号"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="merchantName"
              label="分账商户名"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="channelMerchantNo"
              label="通道商户号"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="splitMerchantNo"
              label="被分账商户号"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="splitMerchantName"
              label="被分账商户名"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="splitChannelMerchantNo"
              label="被分账通道商户号"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="splitRate"
              label="分账比例（参考值）%"
              align="center"
          ></el-table-column>
          <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100">
              <template slot-scope="scope">
                  
                  <el-button
                      type="text"
                      size="small"
                      @click="deletRelation(scope.row)">
                      删除
                  </el-button>
              </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-sizes="[10,20,30,40,50]"
            :page-size='cur_size'
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :current-page.sync="cur_page"
        ></el-pagination>
        </div>
        <!-- 新增弹窗 -->
        <el-dialog
            title="分账关系配置"
            center
            :visible.sync="relationVisible"
            @closed="relationClose"
            @opened="onRelationOpen"
            width="850px"
            class="relationDialog"
            :close-on-click-modal="false">
            <el-form label-position="right" style="padding-left: 40px"  label-width="150px" :rules="relationRule" ref="relationForm" :model="relationForm">
              <el-form-item class="ipt" prop="merchantName" label="分 账 商 户" v-if="userinfo.rolesId == 1 || userinfo.rolesId == 8">
                <el-autocomplete
                style="width: 500px"
                v-model.trim="relationForm.merchantName"
                :fetch-suggestions="merchantslist"
                :trigger-on-focus="false"
                :debounce="300"
                placeholder="分账商户"
                @select="okmerchants">
              </el-autocomplete>
              </el-form-item>
              <el-form-item class="ipt" prop="channelId" label="通 道 类 型">
                <el-select style="width: 500px;" v-model="relationForm.channelId"  placeholder="分账通道" @change="channelChange">
                  <el-option v-for= '(item) in channelArr' :key='item.channelId' :label='item.channelName' :value="item.channelId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="ipt" prop="splitMerchantName" label="被 分 账 商 户">
                <el-autocomplete
                style="width: 500px"
                v-model.trim="relationForm.splitMerchantName"
                :fetch-suggestions="bymerchantslist"
                :trigger-on-focus="false"
                :debounce="300"
                placeholder="被分账商户"
                @select="okBymerchants">
              </el-autocomplete>
              </el-form-item>
              <el-form-item prop="splitRate" label="分账比例(参考值)">
                <el-input placeholder="请输入分账比例" style="width: 500px;" v-model.trim="relationForm.splitRate"></el-input>
                <div style="margin: 5px 0 0px 0px; font-size: 13px;">
                  <i class="el-icon-question" style="margin-right: 5px"></i>
                  <span class="ratio-tips">分账比例取值范围（%）：0.01~100，可精确到2位小数</span>
                </div>
              </el-form-item>
                <el-form-item style="text-align:right; margin-top: 50px;">
                  <el-button type="primary" @click="onSubmit">确定</el-button>
                  <el-button @click="relationClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { getSplitRelation, getMerSplitChannelInfo, saveMerSplitRelaController, deletMerSplitRelaController } from '@/api/splitrelation/splitrelation.js'
import { getChannelList, merchantlist } from '@/api/api'
import { getTimeFn } from '@/utils/getday.js'
export default {
  name: 'SplitRelation',

  data() {
    var checkPercent = (rule, value, cb) => {
        // 分账比例的正则表达式
      const regRatio = /^(0\.(0[1-9]|[1-9]\d{0,1})|[1-9]\d{0,1}(\.\d{1,2})?|100(\.0{1,2})?)$/
      if (regRatio.test(value) || value == undefined || value == '') {
          //合法的分摊比例
          return cb()
      }
      cb(new Error('请填写正确的分账比例'))
    }
    return {
      // 表单校验
    relationRule: {
      splitRate: [
        { validator: checkPercent, trigger: 'blur' }
      ],
      splitMerchantName: [
        { required: true, message: '请选择被分账商户', trigger: 'blur' },
      ],
      channelId: [
        { required: true, message: '请选择通道类型', trigger: 'change' },
      ],
      merchantName: [
        { required: true, message: '请选择分账商户', trigger: 'blur' },
      ],
    },
    pickerOptions: {
      // 设置不能超过未来时间
      // disabledDate: (time) => {
      //   // 设置可选择的日期为今天之后的一个月内
      //   const curDate = (new Date()).getTime()
      //   // 这里算出一个月的毫秒数,这里使用30的平均值,实际中应根据具体的每个月有多少天计算
      //   const day = 31 * 24 * 3600 * 1000
      //   const dateRegion = curDate - day
      //   return time.getTime() > Date.now() - 8.64e7 ||
      //   time.getTime() < dateRegion
      // }
      // 设置不能超过当天的23:59:59
      disabledDate(time) {
      let nowDate = new Date();
      let date = {
          year: nowDate.getFullYear(),
          month: nowDate.getMonth() + 1,
          date: nowDate.getDate(),
      };
      let timeDate =
          date.year + "-" + date.month + "-" + date.date + " 23:59:59";
      let times = new Date(timeDate).getTime();
      return time.getTime() > times;
      },
    },
      key: 0,
      total: 0,
      cur_page: 1,
      cur_size: 10,
      loading: false,
      searchForm: {},
      relationData: [],
      date: "",
      isDisable: false,
      relationVisible: false,
      relationForm: {},
      channelArr: [],
      merchantarrlist: [],
      channelinfo: [],
      userinfo: {}
    };
  },

  created() {
    // const start = new Date().getTime() - ((24 * 60 * 60 * 1000) * 30)
    // const finish = new Date().getTime()
    // let starttime = getTimeFn(start)
    // let finishtime = getTimeFn(finish)
    // const date1 = starttime + " 00:00:00";
    // const date2 = finishtime + " 23:59:59";
    // this.date = [date1, date2];
    this.userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
    if(this.userinfo.rolesId == 5) {
      this.searchForm.merchantId = this.userinfo.fid
    }
    this.getSplitRelationFn()
    this.getChannelFn()
  },

  methods: {
    //修改thead 背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;";
      }
    },
    // 分页导航
    handleCurrentChange(val) {
        this.cur_page = val;
        this.getSplitRelationFn()
        this.$nextTick(() => {
            document.querySelectorAll(".content")[0].scrollTop = "0";
        });
    },
    // 分页数量
    sizechange(val) {
        this.cur_size = val;
        this.getSplitRelationFn()
        this.$nextTick(() => {
            document.querySelectorAll(".content")[0].scrollTop = "0";
        });
    },
    // 刷新
    updateClick() {
      this.loading = true;
      this.getSplitRelationFn()
      this.getChannelFn()
      this.handleCurrentChange(1)
    },
    // 搜索
    soso() {
      this.handleCurrentChange(1)
    },
    // 重置
    reset() {
      this.$refs.searchForm.resetFields()
      // const start = new Date().getTime() - ((24 * 60 * 60 * 1000) * 30)
      // const finish = new Date().getTime()
      // let starttime = getTimeFn(start)
      // let finishtime = getTimeFn(finish)
      // const date1 = starttime + " 00:00:00";
      // const date2 = finishtime + " 23:59:59";
      // this.date = [date1, date2];
    },
    //多选框
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },
    // 通道类型
    async getChannelListFn(id) {
      let res = await getMerSplitChannelInfo(id)
      if(res.code == 405) {
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.channelArr = res.data
      }
    },
    // 获取分账关系列表
    async getSplitRelationFn() {
      let list = {
        merchantId: this.searchForm.merchantId || '',
        merchantNo: this.searchForm.merchantNo || '',
        channelMerchantNo: this.searchForm.channelMerchantNo || '',
        merchantName: this.searchForm.merchantName || '',
        channelId: this.searchForm.channelId || '',
        channelType: this.searchForm.channelType || '',
        channelName: this.searchForm.channelName || '',
        splitMerchantId: this.searchForm.splitMerchantId || '',
        splitMerchantNo: this.searchForm.splitMerchantNo || '',
        splitChannelMerchantNo: this.searchForm.splitChannelMerchantNo || '',
        splitMerchantName: this.searchForm.splitMerchantName || '',
        // startTime: this.date[0],
        // finishTime: this.date[1],
        startTime: '',
        finishTime: '',
        page: this.cur_page,
        size: this.cur_size,
      }
      let res = await getSplitRelation(list)
      if(res.code == 405) {
        this.loading = false;
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.relationData = res.data
        this.cur_page = res.pageInfo.pageCurrent
        this.cur_size = res.pageInfo.pageSize
        this.total = res.pageInfo.recordCount
        this.loading = false
      }
    },
    // 选中通道
    selectChannel(val) {
      this.channelArr.forEach((item) => {
        if(item.channelId == val) {
          this.searchForm.channelType == item.channelType
          this.searchForm.channelName == item.channelName
        }
      })
    },
    // 添加配置
    addRelation() {
      this.relationVisible = true
    },
    // 弹窗动画结束时
    onRelationOpen() {
      if(this.userinfo.rolesId == 5) {
        this.relationForm.merchantId = this.userinfo.fid
        this.getChannelListFn(this.userinfo.fid)
      }
    },
    // 获取商户列表初始化
    merchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.relationForm.merchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    // 被分账商户初始化
    bymerchantslist(queryString, cb) {
    let sosolist = {};
    sosolist = {
        page: 1,
        size: 20,
        merchantName: this.relationForm.splitMerchantName,
    };
    merchantlist(sosolist).then((res) => {
        // console.log(res);
        if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
        } else {
        this.merchantarrlist = [];
        for (var i = 0; i < res.data.length; i++) {
            this.merchantarrlist.push({
            value: res.data[i].merchantName,
            merchantId: res.data[i].id,
            merchantNo: res.data[i].merchantNo
            });
        }
        let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
        // 调用 callback 返回建议列表的数据
        cb(results);
        }
    });
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        );
      };
    },
    // 选择商户
    okmerchants(val) {
        this.relationForm.merchantId = val.merchantId;
        this.relationForm.merchantNo = val.merchantNo
        this.getChannelListFn(val.merchantId)
    },
    // 选择被分账商户
    okBymerchants(val) {
      this.relationForm.splitMerchantId = val.merchantId;
      this.relationForm.splitMerchantNo = val.merchantNo;
    },
    // 获取通道列表
    async getChannelFn() {
      let res = await getChannelList({})
      if(res.code == 405) {
        this.loading = false;
        sessionStorage.removeItem("token");
        this.$router.push("/login");
      } else {
        this.channelinfo = res.data
        this.loading = false
      }
    },
    // 通道选中
    channelChange(val) {
      this.channelArr.forEach((item,index) => {
        if(item.channelId == val) {
          this.relationForm.channelName = item.channelName
          this.relationForm.channelType = item.channelType
        }
      })
    },
    // 提交表单
    onSubmit() {
      this.$refs.relationForm.validate(async(valid) => {
        if(valid) {
          if(this.relationForm.merchantId == this.relationForm.splitMerchantId) {
            this.$message.error('被分账商户不能和分账商户相同')
            return
          } else {
            var date = new Date()
            var Y = date.getFullYear() + '-'
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
            var D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
            var H = date.getHours() + ':'
            var M2 = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
            var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
            var time = Y + M + D + H + M2 + S
            let list = {
              splitListJson: JSON.stringify([
                {
                  merchantId: this.relationForm.splitMerchantId,
                  splitRate: this.relationForm.splitRate
                }
              ]),
              merchantId: this.relationForm.merchantId,
              channelId: this.relationForm.channelId,
              channelName: this.relationForm.channelName,
              channelType: this.relationForm.channelType,
              createTime: time
            }
            let res = await saveMerSplitRelaController(list)
            if(res.code == 405) {
              sessionStorage.removeItem("token");
              this.$router.push("/login");
            } else {
              if(res.code == 200) {
                this.$message.success(res.message)
                this.channelArr = []
                this.relationClose()
                this.getSplitRelationFn()
              } else {
                this.$message.error(res.message)
              }
            }
          }
        }
      })
    },
    // 弹窗关闭事件
    relationClose() {
      this.$refs.relationForm.resetFields()
      this.relationForm = {}
      this.channelArr = []
      this.relationVisible = false
    },
    // 删除分账关系
    deletRelation(val) {
      this.$confirm("是否确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async() => {
        let res = await deletMerSplitRelaController(val.id)
        if(res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          if(res.code == 200) {
            this.$message.success('删除分账关系成功')
            if(this.relationData.length == 1) {
                this.cur_page = this.cur_page - 1
            }
          }
        }
      }).catch(e => e)
      this.getSplitRelationFn()
    },
  },
};
</script>

<style lang="less" scoped>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 30%;
  padding: 0 15px;
  box-sizing: border-box;
}
.rightBox {
    width: 75%;
}
.leftBox > .leftitem,
.rightBox > .leftitem {
  display: flex;
}

.screeningBox .el-form{
    display: flex;
    width: 100%;
}
.ipt {
    width: 70%;
    margin-right: 10px;
    margin-bottom: 15px;
}
.relationDialog{
  text-align: center;
  padding: 0 30px;
}
.addipt {
  width: 100%;
}
</style>